import re

from flask import current_app
from flask import g, jsonify
from flask import request
from info import db
from info.libs.qiuniu import image_storage
from info.utils.common import pro_blue
from . import user_blue
@user_blue.route('/api/v1.0/user/name',methods=['POST'])
@pro_blue
def rename():
    if not g.user:
        return jsonify(errno=1,errmsg='该用户未登陆')
    name=request.json.get('name')
    if not name:
        return jsonify(errno=1,errmsg='名字不能为空')
    g.user.name=name
    db.session.commit()
    return jsonify(errno=0,errmsg='ok')
@user_blue.route('/api/v1.0/user/avatar',methods=['POST'])
@pro_blue
def avatar():
    if not g.user:
        return jsonify(errno=1,errmsg='该用户未登陆')
    avatars=request.files.get('avatar')
    if not avatars:
        return jsonify(errno=1,errmsg='头像不能为空')
    try:
        new_avatar_url=image_storage(avatars.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=1,errmsg='头像上传失败')
    if not new_avatar_url:
        return jsonify(errno=1,errmsg='头像上传失败')
    g.user.avatar_url=new_avatar_url
    db.session.commit()
    data={
        "avatar_url": "http://pkxzow2mg.bkt.clouddn.com/"+new_avatar_url
    }
    return jsonify(errno=0,errmsg='0k',data=data)
@user_blue.route('/api/v1.0/user/auth',methods=['POST','GET'])
@pro_blue
def auth():
    if not g.user:
        return jsonify(errno=1,errmsg='用户未登陆')
    if request.method=='GET':
        if not all([g.user.real_name,g.user.id_card]):
            return jsonify(errno=1,errmsg='该用户未实名认证')
        return jsonify(errno=0,errmsg='ok',data=g.user.to_auth_info())
    if request.method=='POST':
        real_name=request.json.get('real_name')
        id_card=request.json.get('id_card')
        if not all([real_name,id_card]):
            return jsonify(errno=1, errmsg='参数不全')
        if len(real_name) < 2:
            return jsonify(errno=1, errmsg='用户名不能低于2位')
        if not re.match(r"^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$", id_card):
            return jsonify(errno=1, errmsg='身份证错误')
        g.user.real_name=real_name
        g.user.id_card=id_card
        db.session.commit()
        return jsonify(errno=0, errmsg='ok')